<?php
declare (strict_types = 1);

namespace app\model\home;

use app\common\model\BaseModel;
use \libs\Log;

class Notice extends BaseModel
{
    protected $pk = 'id';

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 获得列表
     * @param bool $where
     * @param string $fields
     * @param string|null $order
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($where = true ,string $fields = '*' ,string $order = null ,int $page = 1 ,int $pageSize = 20)
    {
        $data = [
            'count' => 0 ,
            'list'  => []
        ];
        $count = $this->where($where)->count();
        if (empty($count)) {
            return $this->returnRight($data);
        }
        $order = is_null($order) ? $this->pk . ' desc' : $order;
        $list = $this->where($where)
            ->field($fields)
            ->order($order)
            ->page($page , $pageSize)
            ->select();
        $data['count'] = $count;
        $data['list'] = $list;
        return $this->returnRight($data);
    }

    public function getOne(int $id,string $fields='*')
    {
        $user = self::where($this->pk, $id)->field($fields)->find();
        return $user;
    }

    /**
     * 添加
     * @param array $data
     * @return array
     */
    public function add(array $data)
    {
        Log::info('add in parameter' , $data);

        // 6.0自动过滤非数据表字段
        self::create($data);
        return $this->returnSucc('添加成功');
    }

    /**
     * 更新
     * @param array $data
     * @return array
     */
    public function edit(array $data)
    {
        Log::info('edit in parameter' , $data);
        // 更新失败会抛错误到上层，不用判断
        $this->allowField(true)
            ->isUpdate(true)
            ->save($data);
        return $this->returnSucc('编辑成功');
    }


    /**
     * 状态更新：启用，禁用，软删除
     * @param array $data
     * @param int $status
     * @return array
     */
    public function changeStatus(array $data ,int $status)
    {
        $data['status'] = $status;
        $this->allowField(true)
            ->isUpdate(true)
            ->save($data);
        return $this->returnRight();
    }


    /**
     * 硬删除
     * @param int $pkId 数据库主键
     * @return array
     */
    public function del(int $pkId)
    {
        // 更新失败会抛错误到上层，不用判断
        self::destroy($pkId);
        return $this->returnRight();
    }
}
